<template>
  <div
    :contenteditable="true"
    @input="handleInput"
    @focus="handleFocus"
    @blur="handleBlur"
    class="edit-div"
    v-html="text"
  ></div>
</template>
<script>
export default {
  props: {
    text: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      isSelection: false,
      startOffset: 0,
    };
  },
  methods: {
    handleBlur() {
      this.isSelection = false;
    },
    handleFocus() {
      if (!this.isSelection) {
        this.isSelection = true;
        const range = document.createRange();
        range.selectNodeContents(this.$el);
        const sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
      }
    },
    handleInput(event) {
      this.$emit("update:text", event.target.innerText);
    },
  },
};
</script>

<style lang="scss" scoped>
.edit-div {
  padding: 4px;
  width: 100%;
  box-sizing: border-box;
  outline: none;
  text-align: left;
  border: 1px solid #ccc;
  &:focus {
    border: 1px dashed blue;
  }
}
</style>
